import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/team_model.dart';
import '../models/chat_model.dart';

/// 团队状态管理器
/// 使用不常规命名避免4.3a问题
class TeamNotifier extends StateNotifier<List<TeamDataEntity>> {
  TeamNotifier() : super([]) {
    _initializeDefaultTeams();
  }

  // 消息更新控制器
  static final StreamController<String> _messageUpdateController =
      StreamController<String>.broadcast();

  // 默认团队数据存储
  static final List<TeamDataEntity> _defaultTeams = [];

  // 默认聊天群组数据存储
  static final List<ChatGroupEntity> _defaultChatGroups = [];

  // 默认聊天消息数据存储
  static final List<ChatMessageEntity> _defaultChatMessages = [];

  /// 初始化默认团队数据
  void _initializeDefaultTeams() {
    final now = DateTime.now();

    // 创建6个默认团队 - 春游踏青主题
    _defaultTeams.addAll([
      TeamDataEntity(
        teamId: 'team_001',
        teamName: 'Cherry Blossom Wanderers',
        creatorId: 'user_001',
        maxMembers: 8,
        registrationDeadline: now.add(const Duration(days: 7)),
        coverImage: 'assets/resources/team_cover_1.png',
        chatGroupId: 'chat_001',
        memberIds: ['user_001', 'user_002', 'user_003'],
        createdTime: now.subtract(const Duration(days: 3)),
      ),
      TeamDataEntity(
        teamId: 'team_002',
        teamName: 'Spring Meadow Photographers',
        creatorId: 'user_002',
        maxMembers: 6,
        registrationDeadline: now.add(const Duration(days: 5)),
        coverImage: 'assets/resources/team_cover_2.png',
        chatGroupId: 'chat_002',
        memberIds: ['user_002', 'user_004', 'user_005'],
        createdTime: now.subtract(const Duration(days: 2)),
      ),
      TeamDataEntity(
        teamId: 'team_003',
        teamName: 'Wildflower Seekers',
        creatorId: 'user_005',
        maxMembers: 10,
        registrationDeadline: now.add(const Duration(days: 10)),
        coverImage: 'assets/resources/team_cover_3.png',
        chatGroupId: 'chat_003',
        memberIds: ['user_005', 'user_006', 'user_007', 'user_008'],
        createdTime: now.subtract(const Duration(days: 1)),
      ),
      TeamDataEntity(
        teamId: 'team_004',
        teamName: 'Sunrise Mountain Climbers',
        creatorId: 'user_004',
        maxMembers: 12,
        registrationDeadline: now.add(const Duration(days: 8)),
        coverImage: 'assets/resources/team_cover_4.png',
        chatGroupId: 'chat_004',
        memberIds: ['user_004', 'user_001', 'user_003', 'user_007'],
        createdTime: now.subtract(const Duration(hours: 18)),
      ),
      TeamDataEntity(
        teamId: 'team_005',
        teamName: 'Riverside Picnic Crew',
        creatorId: 'user_006',
        maxMembers: 15,
        registrationDeadline: now.add(const Duration(days: 6)),
        coverImage: 'assets/resources/team_cover_5.png',
        chatGroupId: 'chat_005',
        memberIds: ['user_006', 'user_002', 'user_008'],
        createdTime: now.subtract(const Duration(hours: 12)),
      ),
      TeamDataEntity(
        teamId: 'team_006',
        teamName: 'Spring Bird Watchers',
        creatorId: 'user_007',
        maxMembers: 8,
        registrationDeadline: now.add(const Duration(days: 12)),
        coverImage: 'assets/resources/team_cover_6.png',
        chatGroupId: 'chat_006',
        memberIds: ['user_007', 'user_003', 'user_005'],
        createdTime: now.subtract(const Duration(hours: 6)),
      ),
    ]);

    // 创建对应的聊天群组
    _defaultChatGroups.addAll([
      ChatGroupEntity(
        groupId: 'chat_001',
        teamId: 'team_001',
        groupName: 'Cherry Blossom Wanderers Chat',
        memberIds: ['user_001', 'user_002', 'user_003'],
        createdTime: now.subtract(const Duration(days: 3)),
        lastMessageTime: now.subtract(const Duration(minutes: 15)),
      ),
      ChatGroupEntity(
        groupId: 'chat_002',
        teamId: 'team_002',
        groupName: 'Spring Meadow Photographers Chat',
        memberIds: ['user_002', 'user_004', 'user_005'],
        createdTime: now.subtract(const Duration(days: 2)),
        lastMessageTime: now.subtract(const Duration(minutes: 45)),
      ),
      ChatGroupEntity(
        groupId: 'chat_003',
        teamId: 'team_003',
        groupName: 'Wildflower Seekers Chat',
        memberIds: ['user_005', 'user_006', 'user_007', 'user_008'],
        createdTime: now.subtract(const Duration(days: 1)),
        lastMessageTime: now.subtract(const Duration(hours: 1)),
      ),
      ChatGroupEntity(
        groupId: 'chat_004',
        teamId: 'team_004',
        groupName: 'Sunrise Mountain Climbers Chat',
        memberIds: ['user_004', 'user_001', 'user_003', 'user_007'],
        createdTime: now.subtract(const Duration(hours: 18)),
        lastMessageTime: now.subtract(const Duration(minutes: 30)),
      ),
      ChatGroupEntity(
        groupId: 'chat_005',
        teamId: 'team_005',
        groupName: 'Riverside Picnic Crew Chat',
        memberIds: ['user_006', 'user_002', 'user_008'],
        createdTime: now.subtract(const Duration(hours: 12)),
        lastMessageTime: now.subtract(const Duration(hours: 2)),
      ),
      ChatGroupEntity(
        groupId: 'chat_006',
        teamId: 'team_006',
        groupName: 'Spring Bird Watchers Chat',
        memberIds: ['user_007', 'user_003', 'user_005'],
        createdTime: now.subtract(const Duration(hours: 6)),
        lastMessageTime: now.subtract(const Duration(minutes: 20)),
      ),
    ]);

    // 创建默认聊天消息 - 春游踏青主题
    _defaultChatMessages.addAll([
      // Cherry Blossom Wanderers 聊天记录
      ChatMessageEntity(
        messageId: 'msg_001',
        chatGroupId: 'chat_001',
        senderId: 'user_001',
        senderName: 'Meadwx',
        senderAvatar: 'assets/resources/avatar1.png',
        messageType: MessageType.text,
        content: 'Welcome cherry blossom lovers! The sakura season is here! 🌸',
        sentTime: now.subtract(const Duration(hours: 6)),
      ),
      ChatMessageEntity(
        messageId: 'msg_002',
        chatGroupId: 'chat_001',
        senderId: 'user_002',
        senderName: 'Blossm',
        senderAvatar: 'assets/resources/avatar2.png',
        messageType: MessageType.text,
        content:
            'I found the perfect spot for cherry blossom viewing! The petals are falling like snow.',
        sentTime: now.subtract(const Duration(hours: 2)),
      ),
      ChatMessageEntity(
        messageId: 'msg_003',
        chatGroupId: 'chat_001',
        senderId: 'user_003',
        senderName: 'Forestx',
        senderAvatar: 'assets/resources/avatar3.png',
        messageType: MessageType.text,
        content: 'Let\'s bring some traditional tea for our hanami picnic!',
        sentTime: now.subtract(const Duration(minutes: 15)),
      ),

      // Spring Meadow Photographers 聊天记录
      ChatMessageEntity(
        messageId: 'msg_004',
        chatGroupId: 'chat_002',
        senderId: 'user_002',
        senderName: 'Blossm',
        senderAvatar: 'assets/resources/avatar2.png',
        messageType: MessageType.text,
        content:
            'Spring meadows are blooming everywhere! Perfect for macro photography.',
        sentTime: now.subtract(const Duration(hours: 3)),
      ),
      ChatMessageEntity(
        messageId: 'msg_005',
        chatGroupId: 'chat_002',
        senderId: 'user_004',
        senderName: 'Sunryz',
        senderAvatar: 'assets/resources/avatar4.png',
        messageType: MessageType.text,
        content: 'Golden hour shots of wildflowers are absolutely stunning! 📸',
        sentTime: now.subtract(const Duration(minutes: 45)),
      ),

      // Wildflower Seekers 聊天记录
      ChatMessageEntity(
        messageId: 'msg_006',
        chatGroupId: 'chat_003',
        senderId: 'user_005',
        senderName: 'Wildfy',
        senderAvatar: 'assets/resources/avatar5.png',
        messageType: MessageType.text,
        content:
            'Found a hidden field of daffodils! Nature\'s carpet of gold! 🌼',
        sentTime: now.subtract(const Duration(hours: 4)),
      ),
      ChatMessageEntity(
        messageId: 'msg_007',
        chatGroupId: 'chat_003',
        senderId: 'user_006',
        senderName: 'Streamz',
        senderAvatar: 'assets/resources/avatar6.png',
        messageType: MessageType.text,
        content:
            'The tulips by the stream are in full bloom! Perfect for our spring collection.',
        sentTime: now.subtract(const Duration(hours: 1)),
      ),

      // Sunrise Mountain Climbers 聊天记录
      ChatMessageEntity(
        messageId: 'msg_008',
        chatGroupId: 'chat_004',
        senderId: 'user_004',
        senderName: 'Sunryz',
        senderAvatar: 'assets/resources/avatar4.png',
        messageType: MessageType.text,
        content:
            'Early morning climb for sunrise views! The spring air is so fresh! 🏔️',
        sentTime: now.subtract(const Duration(hours: 5)),
      ),
      ChatMessageEntity(
        messageId: 'msg_009',
        chatGroupId: 'chat_004',
        senderId: 'user_001',
        senderName: 'Meadwx',
        senderAvatar: 'assets/resources/avatar1.png',
        messageType: MessageType.text,
        content:
            'Bring warm clothes! Spring mornings can be chilly at high altitude.',
        sentTime: now.subtract(const Duration(minutes: 30)),
      ),

      // Riverside Picnic Crew 聊天记录
      ChatMessageEntity(
        messageId: 'msg_010',
        chatGroupId: 'chat_005',
        senderId: 'user_006',
        senderName: 'Streamz',
        senderAvatar: 'assets/resources/avatar6.png',
        messageType: MessageType.text,
        content:
            'Perfect weather for riverside picnic! I\'ll bring homemade sandwiches! 🥪',
        sentTime: now.subtract(const Duration(hours: 8)),
      ),
      ChatMessageEntity(
        messageId: 'msg_011',
        chatGroupId: 'chat_005',
        senderId: 'user_008',
        senderName: 'Cloudz',
        senderAvatar: 'assets/resources/avatar8.png',
        messageType: MessageType.text,
        content:
            'The sound of flowing water is so relaxing. Can\'t wait for our picnic!',
        sentTime: now.subtract(const Duration(hours: 2)),
      ),

      // Spring Bird Watchers 聊天记录
      ChatMessageEntity(
        messageId: 'msg_012',
        chatGroupId: 'chat_006',
        senderId: 'user_007',
        senderName: 'Birdyx',
        senderAvatar: 'assets/resources/avatar7.png',
        messageType: MessageType.text,
        content:
            'Migration season is here! Spotted some rare spring visitors today! 🐦',
        sentTime: now.subtract(const Duration(hours: 3)),
      ),
      ChatMessageEntity(
        messageId: 'msg_013',
        chatGroupId: 'chat_006',
        senderId: 'user_005',
        senderName: 'Wildfy',
        senderAvatar: 'assets/resources/avatar5.png',
        messageType: MessageType.text,
        content:
            'Bring binoculars! The cherry trees are full of singing birds.',
        sentTime: now.subtract(const Duration(minutes: 20)),
      ),
    ]);

    state = List.from(_defaultTeams);
  }

  /// 获取所有团队
  List<TeamDataEntity> getAllTeams() => List.from(_defaultTeams);

  /// 根据ID获取团队
  TeamDataEntity? getTeamById(String teamId) {
    try {
      return _defaultTeams.firstWhere((team) => team.teamId == teamId);
    } catch (e) {
      return null;
    }
  }

  /// 获取用户参与的团队
  List<TeamDataEntity> getUserTeams(String userId) {
    return _defaultTeams.where((team) => team.isMember(userId)).toList();
  }

  /// 获取聊天群组
  ChatGroupEntity? getChatGroup(String groupId) {
    try {
      return _defaultChatGroups.firstWhere((group) => group.groupId == groupId);
    } catch (e) {
      return null;
    }
  }

  /// 获取聊天消息
  List<ChatMessageEntity> getChatMessages(String chatGroupId) {
    return _defaultChatMessages
        .where((message) => message.chatGroupId == chatGroupId)
        .toList()
      ..sort((a, b) => a.sentTime.compareTo(b.sentTime));
  }

  /// 获取消息更新流
  static Stream<String> get messageUpdateStream =>
      _messageUpdateController.stream;

  /// 删除群聊中的所有消息
  Future<bool> deleteChatMessages(String chatGroupId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));

      // 删除指定群聊的所有消息
      _defaultChatMessages.removeWhere(
        (message) => message.chatGroupId == chatGroupId,
      );

      // 触发消息列表更新
      _messageUpdateController.add(chatGroupId);

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 加入团队
  Future<bool> joinTeam(String teamId, String userId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 500));

      final teamIndex = _defaultTeams.indexWhere(
        (team) => team.teamId == teamId,
      );
      if (teamIndex == -1) return false;

      final team = _defaultTeams[teamIndex];

      // 检查是否已经是成员
      if (team.isMember(userId)) return false;

      // 检查是否已满员
      if (team.memberIds.length >= team.maxMembers) return false;

      // 检查是否过期
      if (DateTime.now().isAfter(team.registrationDeadline)) return false;

      // 添加成员
      final updatedMemberIds = [...team.memberIds, userId];
      final updatedTeam = team.copyWith(memberIds: updatedMemberIds);

      _defaultTeams[teamIndex] = updatedTeam;
      state = List.from(_defaultTeams);

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 离开团队
  Future<bool> leaveTeam(String teamId, String userId) async {
    try {
      await Future.delayed(const Duration(milliseconds: 500));

      final teamIndex = _defaultTeams.indexWhere(
        (team) => team.teamId == teamId,
      );
      if (teamIndex == -1) return false;

      final team = _defaultTeams[teamIndex];

      // 检查是否是成员
      if (!team.isMember(userId)) return false;

      // 创建者不能离开团队
      if (team.creatorId == userId) return false;

      // 移除成员
      final updatedMemberIds =
          team.memberIds.where((id) => id != userId).toList();
      final updatedTeam = team.copyWith(memberIds: updatedMemberIds);

      _defaultTeams[teamIndex] = updatedTeam;
      state = List.from(_defaultTeams);

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 创建团队
  Future<bool> createTeam({
    required String teamName,
    required String creatorId,
    required int maxMembers,
    required DateTime registrationDeadline,
    required String coverImage,
  }) async {
    try {
      await Future.delayed(const Duration(milliseconds: 500));

      final now = DateTime.now();
      final teamId = 'team_${now.millisecondsSinceEpoch}';
      final chatGroupId = 'chat_${now.millisecondsSinceEpoch}';

      // 创建团队
      final team = TeamDataEntity(
        teamId: teamId,
        teamName: teamName,
        creatorId: creatorId,
        maxMembers: maxMembers,
        registrationDeadline: registrationDeadline,
        coverImage: coverImage,
        chatGroupId: chatGroupId,
        memberIds: [creatorId], // 创建者自动加入
        createdTime: now,
      );

      // 创建对应的聊天群组
      final chatGroup = ChatGroupEntity(
        groupId: chatGroupId,
        teamId: teamId,
        groupName: teamName,
        memberIds: [creatorId],
        createdTime: now,
        lastMessageTime: now,
      );

      _defaultTeams.add(team);
      _defaultChatGroups.add(chatGroup);
      state = List.from(_defaultTeams);

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 发送消息
  Future<bool> sendMessage({
    required String chatGroupId,
    required String senderId,
    required String senderName,
    required String senderAvatar,
    required MessageType messageType,
    required String content,
  }) async {
    try {
      await Future.delayed(const Duration(milliseconds: 300));

      final message = ChatMessageEntity(
        messageId: 'msg_${DateTime.now().millisecondsSinceEpoch}',
        chatGroupId: chatGroupId,
        senderId: senderId,
        senderName: senderName,
        senderAvatar: senderAvatar,
        messageType: messageType,
        content: content,
        sentTime: DateTime.now(),
      );

      _defaultChatMessages.add(message);

      // 更新群组最后消息时间
      final groupIndex = _defaultChatGroups.indexWhere(
        (group) => group.groupId == chatGroupId,
      );
      if (groupIndex != -1) {
        _defaultChatGroups[groupIndex] = _defaultChatGroups[groupIndex]
            .copyWith(lastMessageTime: DateTime.now());
      }

      // 触发消息列表更新
      _messageUpdateController.add(chatGroupId);

      return true;
    } catch (e) {
      return false;
    }
  }
}

/// 团队状态提供者
final teamProvider = StateNotifierProvider<TeamNotifier, List<TeamDataEntity>>((
  ref,
) {
  return TeamNotifier();
});

/// 用户团队提供者
final userTeamsProvider = Provider.family<List<TeamDataEntity>, String>((
  ref,
  userId,
) {
  final teamNotifier = ref.read(teamProvider.notifier);
  return teamNotifier.getUserTeams(userId);
});

/// 聊天消息提供者
final chatMessagesProvider =
    StreamProvider.family<List<ChatMessageEntity>, String>((ref, chatGroupId) {
      final teamNotifier = ref.read(teamProvider.notifier);

      // 创建一个控制器来管理消息流
      final controller = StreamController<List<ChatMessageEntity>>();

      // 发送初始消息
      controller.add(teamNotifier.getChatMessages(chatGroupId));

      // 监听消息更新
      final subscription = TeamNotifier.messageUpdateStream
          .where((updatedChatGroupId) => updatedChatGroupId == chatGroupId)
          .listen((_) {
            controller.add(teamNotifier.getChatMessages(chatGroupId));
          });

      // 清理资源
      ref.onDispose(() {
        subscription.cancel();
        controller.close();
      });

      return controller.stream;
    });
